package example.ble;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.myapplication.BuildConfig;
import com.example.administrator.myapplication.R;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static android.os.Build.VERSION_CODES.LOLLIPOP;

public class MainActivity extends AppCompatActivity {

    private BluetoothAdapter mBluetoothAdapter;
    private List<ScanFilter> mFilterList = new ArrayList<>();
    private ScanSettings mScanSettings;
    private BluetoothLeScanner mBluetoothScanner;
    private TableLayout devTable;

    private MySurface surface;
    private List<BluetoothDevice> mDeviceList = new ArrayList<>();
    private BluetoothGatt mGatt;
    private boolean isSanning = false;

    private final static String SERVICE_UUID = "0000ffd0-0000-1000-8000-00805f9b34fb";
    private final static String CHAR_MOVE_UUID = "0000ffd1-0000-1000-8000-00805f9b34fb";

    private BluetoothGattCharacteristic charMove;

    static String[]  PERMISSIONS = new String[] {
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
    };

    @RequiresApi(LOLLIPOP)
    private ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {

            BluetoothDevice dev = result.getDevice();
            if(dev != null && dev.getName() != null) {
                String macAddr = dev.getAddress();

                for (BluetoothDevice d: mDeviceList) {
                    if(d.getAddress().equals(dev.getAddress())) {
                        return;
                    }
                }
                mDeviceList.add(dev);
                updateDeviceTable();
            }
        }
    };

    @RequiresApi(LOLLIPOP)
    private void updateDeviceTable() {

        devTable.removeAllViews();

        for (final BluetoothDevice dev: mDeviceList) {
            TableRow row = new TableRow(this);
            row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                    TableRow.LayoutParams.WRAP_CONTENT));

            TextView nameTv = new TextView(this);
            nameTv.setText(dev.getName());
            nameTv.setTextSize(20);

            TextView macTv = new TextView(this);
            macTv.setText(dev.getAddress());

            Button btn = new Button(this);
            btn.setText("连接");
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    connectToDevice(dev);
                }
            });

            row.addView(nameTv);
            row.addView(macTv);
            row.addView(btn);

            devTable.addView(row);
        }

    }

    private BluetoothGattCallback mGattCallBack = new BluetoothGattCallback() {

        @Override
                public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    if(characteristic.getUuid().toString().equals(CHAR_MOVE_UUID)) {

                        final byte[] speed = characteristic.getValue();

                        surface.setMove(speed[0] * 1.0);
                        surface.setRotate(speed[1] * 1.0);

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                Toast.makeText(MainActivity.this, "speed[0]=" + speed[0] +" speed[1]=" + speed[1], Toast.LENGTH_LONG).show();
                            }
                        });

                    }
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            switch (newState) {
                case BluetoothGatt.STATE_CONNECTED:
                    gatt.discoverServices();
                    break;
                case BluetoothGatt.STATE_DISCONNECTED:
                    gatt.close();
                    break;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if(status == BluetoothGatt.GATT_SUCCESS) {
                List<BluetoothGattService> serviceList = gatt.getServices();
                for (BluetoothGattService service: serviceList) {
                   if(service.getUuid().toString().equals(SERVICE_UUID)) {
                       charMove = service.getCharacteristic(UUID.fromString(CHAR_MOVE_UUID) );
                       final boolean result = gatt.setCharacteristicNotification(charMove, true);

                       runOnUiThread(new Runnable() {
                           @Override
                           public void run() {
                               if(result) {
                                   Toast.makeText(MainActivity.this, "character move notify 开启 成功", Toast.LENGTH_LONG).show();
                                   BluetoothGattDescriptor descriptor = charMove.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
                                   descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                                   mGatt.writeDescriptor(descriptor);
                               } else {
                                   Toast.makeText(MainActivity.this, "character move notify 开启 失败", Toast.LENGTH_LONG).show();
                               }
                           }
                       });

                   }
                }
            }
        }
    };

    @RequiresApi(LOLLIPOP)
    private void connectToDevice(BluetoothDevice dev) {
        //停止扫描
        if(isSanning) {
            scanBLEDevice(false);
        }
        if(mGatt != null) {
            mGatt.close();
            mGatt = null;
        }
        mGatt = dev.connectGatt(this,  false,  mGattCallBack );
    }

    private boolean hasPermission(String[] permissions) {
        for (String p: permissions) {
            int result = ContextCompat.checkSelfPermission(this, p);
            if( result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if( !hasPermission(PERMISSIONS))  {
            ActivityCompat.requestPermissions(this, PERMISSIONS, 0);
        }

        setContentView(R.layout.activity_main);

        BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);

        mBluetoothAdapter = bluetoothManager.getAdapter();

        ScanFilter filter = null;
        if (android.os.Build.VERSION.SDK_INT >= LOLLIPOP) {
            filter = new ScanFilter.Builder().build();
            mScanSettings = new ScanSettings.Builder().build();
        }
        mFilterList.add(filter);

        devTable = findViewById(R.id.table);
        surface = findViewById(R.id.surface);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if(mBluetoothAdapter != null) {
            if(!mBluetoothAdapter.isEnabled()) {
                Toast.makeText(this, "请开启蓝牙", Toast.LENGTH_LONG).show();
                //finish();
            } else {
                if (Build.VERSION.SDK_INT >= LOLLIPOP) {
                    mBluetoothScanner = mBluetoothAdapter.getBluetoothLeScanner();
                    //TODO 扫描蓝牙设备
                    scanBLEDevice(true);
                }
            }
        }
    }

    @RequiresApi(LOLLIPOP)
    private void scanBLEDevice(boolean enable) {
        if(mBluetoothScanner != null) {
            if(enable) {
                mBluetoothScanner.startScan(mFilterList, mScanSettings, mScanCallback);
                isSanning = true;
            } else {
                isSanning = false;
                mBluetoothScanner.stopScan(mScanCallback);
            }
        }
    }
}
